﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Windows.Navigation;
using System.Xml.Linq;
using System.IO.IsolatedStorage;
using System.IO;
using System.Text.RegularExpressions;
using System.Xml;

namespace Senior_Project
{
    public partial class MainPage : PhoneApplicationPage
    {
        List<menu> MenuList = new List<menu>();
        string foodname, fid;
        string[] nutrition;

        // Constructor
        public MainPage()
        {
            InitializeComponent();

            // Set the data context of the listbox control to the sample data
            DataContext = App.ViewModel;
            this.Loaded +=new RoutedEventHandler(MainPage_Loaded);
			
        }

        static string[] SplitWords(string s)
        {
            //
            // Split on all non-word characters.
            // ... Returns an array of all the words.
            //
            return Regex.Split(s, @"\W+");
            // @      special verbatim string syntax
            // \W+    one or more non-word characters together
        }

        // Load data for the ViewModel Items
        private void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (!App.ViewModel.IsDataLoaded)
            {
                App.ViewModel.LoadData();
               
            }   
        }



        // *************************************** event in panorama item 1 ********************************************
        private void profile_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            //--- profile in pano1 ---
            NavigationService.Navigate(new Uri("/ProfilePage.xaml", UriKind.RelativeOrAbsolute));
        }

        private void history_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            // --- my history in pano1 ---
            NavigationService.Navigate(new Uri("/HistoryPage.xaml", UriKind.RelativeOrAbsolute));
        }


        // logout click >> to delete userXML.xml file !!
        private void logout_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            try
            {
                using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    // delete file !!
                    myIsolatedStorage.DeleteFile("userXML.xml");
                }
            }
            catch { MessageBox.Show("File not found !"); }

            NavigationService.Navigate(new Uri("/LoginPage.xaml", UriKind.Relative));
        }
        //**************************************************************************************************************




        // *************************************** event in panorama item 2 ********************************************
        private void QRscan_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            // --- QR scanner call camera in pano2 ---
            NavigationService.Navigate(new Uri("/CameraPage.xaml", UriKind.RelativeOrAbsolute));
            //NavigationService.Navigate(new Uri("/TestPage.xaml", UriKind.RelativeOrAbsolute));

        }
        //**************************************************************************************************************




        // *************************************** event in panorama item 3 ********************************************
        private void showMenu_Checked(object sender, System.Windows.RoutedEventArgs e)
        {
        	//--- show menu guide ---
			showMenu.Content = "Show";
            XElement xml = XElement.Load("menu.xml");
           

            // feed data from "menu.xml" file
            var items = from item in xml.Descendants("food")
                        select new menu
                        {
                            FID = item.Element("ID").Value,
                            UserImage = item.Element("picture").Value,
                            Text = item.Element("name").Value,
                            DateTime = item.Element("data").Value
                        };

            // show to ListBox
            lstTwitter.ItemsSource = items;

            foreach (var menuItem in items)
            {
                MenuList.Add(menuItem);
            }
        }

        private void showMenu_Unchecked(object sender, System.Windows.RoutedEventArgs e)
        {
        	//--- hide menu guide ---
			showMenu.Content = "Hide";
            lstTwitter.ItemsSource = "";
        }
        //**************************************************************************************************************



        // page exit
        private void PhoneApplicationPage_BackKeyPress(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (MessageBox.Show("Do you really want to exit?", "Message", MessageBoxButton.OKCancel) != MessageBoxResult.OK)
            {
                e.Cancel = true;
            }
            else
            {
                if (NavigationService.CanGoBack)
                {
                    while (NavigationService.RemoveBackEntry() != null)
                    {
                        NavigationService.RemoveBackEntry();
                    }
                }
            }
        }

        private void lstTwitter_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            int index = lstTwitter.SelectedIndex;

            menu detail = MenuList[index];
            foodname = detail.Text;
            fid = detail.FID;
            nutrition = SplitWords(detail.DateTime);

            string result = "Name : " + foodname + "\n" +
                            "Weight : " + nutrition[1] + " g." + "\n" +
                            "Calory : " + nutrition[4] + " kcal." + "\n" +
                            "Protein : " + nutrition[7] + " g." + "\n" +
                            "Fat : " + nutrition[10] + " g." + "\n" +
                            "Carbohydrate : " + nutrition[13] + " g.";

            if (MessageBox.Show(result, "Result", MessageBoxButton.OKCancel) != MessageBoxResult.Cancel)
            {
                // call saveData method
                saveData();
            }
            else { }
            //string test = nutrition[1] +" "+ nutrition[4] +" "+ nutrition[7] +" "+ nutrition[10] +" "+ nutrition[13];
            //MessageBox.Show(test);
        }


        //******************************************** saveData() method ****************************************************
        public void saveData()
        {
            // set variable refer to IsolatedStorageFile
            using (IsolatedStorageFile myIsolated = IsolatedStorageFile.GetUserStoreForApplication())
            {
                // check file exist >> 
                // file exits -> update TempXML.xml (add element items) 
                if (myIsolated.FileExists("TempXML.xml"))
                {
                    // set variable refer to XDocument
                    XDocument doc;
                    using (IsolatedStorageFileStream isoStream = myIsolated.OpenFile("TempXML.xml", FileMode.Open, FileAccess.Read))
                    {
                        // load TempXML.xml in Open mode
                        doc = XDocument.Load(isoStream);
                        DateTime datetime = DateTime.Now;
                        string[] w = SplitWords(datetime.ToString());
                        string date = w[2] + "-" + w[0] + "-" + w[1];
                        string time = w[3] + ":" + w[4] + ":" + w[5] + " " + w[6];


                        // create element and value
                        XElement element = new XElement("food",
                                                new XElement("date", date),
                                                new XElement("time", time),
                                                new XElement("id", fid),
                                                new XElement("name", foodname),
                                                new XElement("weight", nutrition[1]),
                                                new XElement("calory", nutrition[4]),
                                                new XElement("protein", nutrition[7]),
                                                new XElement("fat", nutrition[10]),
                                                new XElement("carbohydrate", nutrition[13]),
                                                new XElement("calcium", 0),
                                                new XElement("phosphorus", 0),
                                                new XElement("iron", 0)
                                            );
                        // add element to Root document
                        doc.Root.Add(new XElement(element));
                    }

                    // set variable refer to IsolatedStorageFileStream and StreamWriter
                    using (IsolatedStorageFileStream isolatedStorageFileStream = myIsolated.OpenFile("TempXML.xml", FileMode.Open, FileAccess.Write))
                    {
                        using (var file = new StreamWriter(isolatedStorageFileStream))
                        {
                            // save new element to file
                            doc.Save(file);
                        }
                    }

                }
                // file no exit -> create TempXML.xml file
                else
                {
                    // set variable refer to IsolatedStorageFileStream
                    using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream("TempXML.xml", FileMode.Create, FileAccess.Write, myIsolated))
                    {
                        // set variable refer to XmlWriterSetting
                        XmlWriterSettings setting = new XmlWriterSettings();
                        setting.Indent = true;

                        // set variable refer to XmlWriter
                        using (XmlWriter writer = XmlWriter.Create(isoStream, setting))
                        {
                            // create element and value
                            DateTime datetime = DateTime.Now;
                            string[] w = SplitWords(datetime.ToString());
                            string date = w[2] + "-" + w[0] + "-" + w[1];
                            string time = w[3] + ":" + w[4] + ":" + w[5] + " " + w[6];

                            writer.WriteStartElement("n", "nutrition", "upn:nutrition");

                            writer.WriteStartElement("food");

                            writer.WriteStartElement("date");
                            writer.WriteString(date);
                            writer.WriteEndElement();

                            writer.WriteStartElement("time");
                            writer.WriteString(time);
                            writer.WriteEndElement();

                            writer.WriteStartElement("id");
                            writer.WriteString(fid);
                            writer.WriteEndElement();

                            writer.WriteStartElement("name");
                            writer.WriteString(foodname);
                            writer.WriteEndElement();

                            writer.WriteStartElement("weight");
                            writer.WriteString(nutrition[1]);
                            writer.WriteEndElement();

                            writer.WriteStartElement("calory");
                            writer.WriteString(nutrition[4]);
                            writer.WriteEndElement();

                            writer.WriteStartElement("protein");
                            writer.WriteString(nutrition[7]);
                            writer.WriteEndElement();

                            writer.WriteStartElement("fat");
                            writer.WriteString(nutrition[10]);
                            writer.WriteEndElement();

                            writer.WriteStartElement("carbohydrate");
                            writer.WriteString(nutrition[13]);
                            writer.WriteEndElement();

                            writer.WriteStartElement("calcium");
                            writer.WriteString("0");
                            writer.WriteEndElement();

                            writer.WriteStartElement("phosphorus");
                            writer.WriteString("0");
                            writer.WriteEndElement();

                            writer.WriteStartElement("iron");
                            writer.WriteString("0");
                            writer.WriteEndElement();

                            writer.WriteEndElement();

                            // end document
                            writer.WriteEndDocument();

                            // writer to file
                            writer.Flush();
                        }
                    }
                }
                //*************************************************************************************************************



                //#############################################################################################################
                // ******************************** for check xml file show to MessageBox *************************************
                string test;
                try
                {
                    using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        IsolatedStorageFileStream isoFileStream = myIsolatedStorage.OpenFile("TempXML.xml", FileMode.Open);
                        using (StreamReader reader = new StreamReader(isoFileStream))
                        {
                            test = reader.ReadToEnd();
                            MessageBox.Show(test, "result", MessageBoxButton.OK);
                        }
                    }
                }
                catch { MessageBox.Show("File not found !"); }
                //************************************************************************************************************
                //myIsolated.DeleteFile("TempXML.xml");
                //############################################################################################################
            }
        }

    }
}